using System;
using System.Windows.Forms;
using Microsoft.Xna.Framework.Graphics;

namespace RebelStar.Engine.GameView
{
    class GraphicsDeviceService : IGraphicsDeviceService, IDisposable
    {
        private GraphicsDevice device;
        private readonly Control viewPort;

        public GraphicsDeviceService(Control control)
        {
            this.viewPort = control;
            this.viewPort.Resize += viewPort_Resize;
        }

        #region IGraphicsDeviceService Members

        public event EventHandler DeviceCreated;
        public event EventHandler DeviceDisposing;
        public event EventHandler DeviceReset;
        public event EventHandler DeviceResetting;

        public GraphicsDevice GraphicsDevice
        {
            get { return this.device; }
        }

        #endregion

        public void CreateDevice()
        {
            PresentationParameters pp = new PresentationParameters();
            pp.BackBufferCount = 1;
            pp.IsFullScreen = false;
            pp.SwapEffect = SwapEffect.Discard;
            pp.BackBufferWidth = viewPort.Width;
            pp.BackBufferHeight = viewPort.Height;

            pp.AutoDepthStencilFormat = DepthFormat.Depth24Stencil8;
            pp.EnableAutoDepthStencil = true;
            pp.PresentationInterval = PresentInterval.Default;
            pp.BackBufferFormat = SurfaceFormat.Unknown;
            pp.MultiSampleType = MultiSampleType.None;

            device = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, DeviceType.Hardware, this.viewPort.Handle, pp);

            if (DeviceCreated!=null)
                DeviceCreated(this, EventArgs.Empty);
        }
        public void Reset(PresentationParameters pp)
        {
            if (DeviceResetting != null)
                DeviceResetting(this, EventArgs.Empty);

            device.Reset(pp);

            if (DeviceReset != null)
                DeviceReset(this, EventArgs.Empty);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (DeviceDisposing != null)
                DeviceDisposing(this, EventArgs.Empty);
            device.Dispose();
        }

        #endregion

        void viewPort_Resize(object sender, EventArgs e)
        {
            if (viewPort.Width == 0 || viewPort.Height == 0)
                return;

            device.PresentationParameters.BackBufferWidth = viewPort.Width;
            device.PresentationParameters.BackBufferHeight = viewPort.Height;

            this.Reset(device.PresentationParameters);

            viewPort.Invalidate();
        }
    }
}
